package com.example.http.consumer.client;

import com.example.http.consumer.bean.User;
import com.example.http.consumer.common.Result;
import com.example.http.consumer.common.XStreamUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

@SuppressWarnings({"rawtypes"})
public class XMLClient {

    private static final String PREFIX_URL = "http://localhost:8070/provider/xmlServlet";

    public static void main(String[] args) throws IOException {
        XMLClient xmlClient = new XMLClient();
        System.out.println("xmlClient.get ---> " + xmlClient.get(1));
        User user = new User("xml", 15);
        System.out.println("xmlClient.add ---> " + xmlClient.add(user));
    }

    public User add(User user) throws IOException {
        String urlString = PREFIX_URL + "?requestType=add";
        Result result = XStreamUtil.fromXML(postRequest(urlString, user), Result.class);
        return (User) result.getData();
    }

    public User get(Integer id) throws IOException {
        String urlString = PREFIX_URL + "?requestType=get&id=" + id;
        Result result = XStreamUtil.fromXML(postRequest(urlString, null), Result.class);
        return (User) result.getData();
    }

    private String postRequest(String urlString, Object data) throws IOException {
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");
        try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
            out.write(XStreamUtil.toXML(data));
            out.flush();
        }
        StringBuilder stringBuilder;
        try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            stringBuilder = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        return stringBuilder.toString();
    }
}
